package com.yushu.common.shiro;

import com.yushu.authority.pojo.bo.PmUser;
import com.yushu.authority.pojo.vo.PmUserVO;
import com.yushu.common.util.bean.Father2Son;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;


 /**
 * Shiro工具类
 * @author test
 * @CreateDate 2020-12-03 15:47:25
 */
public class ShiroUtil {


    /**
     * <pre>
     *        获取当前Session中的用户
     * </pre>
     *
     * @author test
     * @since 2019/11/4  13:14
     **/
    public static PmUserVO getSessionUser() {

        Subject subject = SecurityUtils.getSubject();

        if (subject != null) {
            Object object = subject.getPrincipal();
            if (object != null) {
                PmUser user = (PmUser) object;
                PmUserVO userVO = new PmUserVO();
                Father2Son.Copy(user, userVO);
                return userVO;
            }
        }
        return null;
    }

    /**
     * 获取当前用户ID
     *
     * @return
     */
    public static String getSessionUid() {
        PmUser sysUser = getSessionUser();
        if (sysUser != null) {
            return sysUser.getId();
        }
        return null;
    }


    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static Session getSession() {
        return getSubject().getSession();
    }


    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    public static String getCaptcha(String key, boolean isUsed) {
        String captcha = getSessionAttribute(key).toString();
        if (isUsed) {
            getSession().removeAttribute(key);
        }
        return captcha;
    }
}
